package com.wushi.lenovo.asia5b.app_ui.shopcar.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.refresh.AutoRefreshLayout;
import com.mvp.refresh.RefreshViewManager;
import com.mvp.utils.StringUtils;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.ShopRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.ShopCarFragmentView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.ShopCarFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.AddShopCarEvent;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.OrderPayEvent;
import com.wushi.lenovo.asia5b.app_event.PlaceOrderEvent;
import com.wushi.lenovo.asia5b.app_event.ShopCarCoutEvent;
import com.wushi.lenovo.asia5b.app_model.good.ShopModel;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModel;
import com.wushi.lenovo.asia5b.app_model.h5.H5ShopBean;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_ui.good.activity.OrderCheckPiActivity;
import com.wushi.lenovo.asia5b.app_ui.h5.GoodsDetailsActivity;
import com.wushi.lenovo.asia5b.app_ui.other.bean.ShopUpdateListener;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.CancelSureDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ShopCarNoticeDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.shop.ShopUpdateDialogFragment;
import com.wushi.lenovo.asia5b.app_ui.shopcar.adapter.ShopCarShopAdapter;
import com.wushi.lenovo.asia5b.app_ui.shopcar.listener.ShopCarListener;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/2/17.
 * 普通商品购物车
 */
public class ShopCarFragment extends BaseMvpFragment<ShopCarFragmentView, ShopCarFragmentPresenter>
        implements ShopCarFragmentView, ShopUpdateListener {
    @BindView(R.id.recyclerview_shopcar)
    public RecyclerView mRecyclerView;
    @BindView(R.id.auto_shop)
    public AutoRefreshLayout auto;
    @BindView(R.id.bt_shopcar_submit)
    public Button bt_shopcar_submit;
    @BindView(R.id.tv_shopcar_totalprice)
    public TextView tv_shopcar_totalprice;
    @BindView(R.id.iv_shopcar_checkall)
    public ImageView iv_shopcar_checkall;
    @BindView(R.id.tv_shopcar_note)
    public TextView tv_shopcar_note;
    @BindView(R.id.cons_shop_bottom)
    public ConstraintLayout cons_shop_bottom;
    public View emptyView;

    public ShopCarShopAdapter mAdapter;
    public final List<ShopModel> mDatas = new ArrayList<>();//列表数据

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_shopcar;
    }

    public static ShopCarFragment newInstance(Context context) {
        return (ShopCarFragment) Fragment.instantiate(context, ShopCarFragment.class.getName(), null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        initView();
        initEvent();
        resetView();
    }

    /**
     * @return 是否是代购商品
     */
    protected boolean isDaigou() {
        return true;
    }


    /**
     * 懒加载初始化数据
     */
    @Override
    protected void lazyFetchData() {
        initData();
    }

    /**
     * 初始化视图
     */
    @Override
    protected void initView() {
        if (isDaigou()) {
            EyeUtils.setLinkText(mActivity, getString(R.string.shopcar_notice), getString(R.string.shopcar_daigou),
                    tv_shopcar_note, WebUrlType.shopcar_daigou);
        } else {
            EyeUtils.setLinkText(mActivity, getString(R.string.shopcar_pi_notice), getString(R.string.shopcar_pi_notice_key),
                    tv_shopcar_note, WebUrlType.shopcar_pi);
        }

        if (auto != null) {
            ((RefreshViewManager) mActivity).addView(auto);
        }

        //创建空视图
        creatEmptyView();

        mAdapter = new ShopCarShopAdapter(mDatas, shopCarListener);


        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

        //无加载更多
        if (auto != null)
            auto.setEnableLoadMore(false);


        if (auto != null)
            auto.autoRefresh();

    }

    /**
     * 没有用户登录的情况下,重置界面状态,并且无任何数据
     */
    private void resetView() {
        mDatas.clear();
        mAdapter.notifyDataSetChanged();
        setBottomView();
    }

    /**
     * 创建空布局视图
     */
    private void creatEmptyView() {
        emptyView = View.inflate(getContext(), R.layout.empty_wish, null);
        ImageView empty_icon = emptyView.findViewById(R.id.empty_icon);
        TextView tv_empty_content = emptyView.findViewById(R.id.tv_empty_content);
        TextView tv_empty_start = emptyView.findViewById(R.id.tv_empty_start);
        empty_icon.setImageResource(R.drawable.icon_shopcar_gray);
        tv_empty_content.setText(R.string.shopcar_empth);
        tv_empty_start.setOnClickListener(v -> {
            getActivity().finish();
        });
    }

    /**
     * 设置底部视图
     */
    protected void setBottomView() {
        //选中数据
        List<GoodsModel> selectData = getSelectData();
        if (selectData.size() != 0) {
            //可以确认付款
            bt_shopcar_submit.setEnabled(true);
            //总价格
            double totalF = 0f;
            //货币单位 "RM"
            for (GoodsModel model : selectData) {
                totalF += model.getTotalF();
            }
            if (isDaigou()) {//代购商品还得计算中国物流价格
                Timber.d("--->>>>>>>>---中国物流总费用:" + chinaFeeTotal);
                totalF += chinaFeeTotal;
            }
            //不带单位的总价格
            String totalF_text = StringUtils.formatNum(totalF + "", 2);
            //带单位的总价格
            String total_text = String.format("RM %s", totalF_text);
            //设置总价格
            tv_shopcar_totalprice.setText(total_text);
            //设置是否全选
            iv_shopcar_checkall.setSelected(goodsTotal() == selectData.size());
        } else {
            tv_shopcar_totalprice.setText("RM 0.00");
            iv_shopcar_checkall.setSelected(false);
            bt_shopcar_submit.setEnabled(false);
        }
    }

    /**
     * 初始化加载数据
     */
    @Override
    protected void initData() {

    }

    /**
     * 获取购物车商品列表
     *
     * @param refresh <=0刷新
     */
    protected void getGoodList(int refresh) {
        getPresenter().getGoodList(refresh, mDatas);
    }

    /**
     * 更新商品属性回调
     *
     * @param h5ShopBean
     * @param model
     */
    @Override
    public void callBack(H5ShopBean h5ShopBean, GoodsModel model) {
        if (h5ShopBean != null) {
            updateGoodForAttr(model, h5ShopBean);
        }
    }


    /**
     * 获取选中商品的价格
     * 1,点击选中框时
     * 2,点击全选框时
     */
    public void getCharges() {
        /**
         * 本地计算总价格
         */
        setBottomView();
    }

    protected double chinaFeeTotal = 0.0;//与getSelectData() 一一对应

    /**
     * @return 选中的商品集合
     */
    protected List<GoodsModel> getSelectData() {
        chinaFeeTotal = 0.0;
        List<GoodsModel> selectData = new ArrayList<>();
        for (ShopModel shopModel : mDatas) {
            boolean isAddFee = false;//本店铺的物流费用是否被+过
            List<GoodsModel> goodsModelList = shopModel.products;
            if (goodsModelList != null) {
                for (GoodsModel model : goodsModelList) {
                    if (model.isChecked() && model.canCheck()) {
                        selectData.add(model);
                        if (!isAddFee) {
                            isAddFee = true;
                            chinaFeeTotal += shopModel.domestic_fee;
                        }
                    }
                }
            }
        }

        return selectData;
    }

    /**
     * @return 选中的商品集合
     */
    protected List<Integer> getSelectIdList() {
        List<Integer> selectData = new ArrayList<>();
        for (ShopModel shopModel : mDatas) {
            List<GoodsModel> goodsModelList = shopModel.products;
            if (goodsModelList != null) {
                for (GoodsModel model : goodsModelList) {
                    if (model.isChecked() && model.canCheck()) {
                        selectData.add(model.getId());
                    }
                }
            }
        }

        return selectData;
    }

    /**
     * 删除商品
     */
    public void delete() {
        final List<GoodsModel> selectData = getSelectData();
        if (selectData.size() == 0) {
            return;
        }
        ShopCarNoticeDialog noticeDialog = new ShopCarNoticeDialog(getContext(),
                getString(R.string.shopcar_deletenotice_title),
                getString(R.string.shopcar_deletenotice_content));
        noticeDialog.setCallBack(new WCallBack<Boolean>() {
            @Override
            public void callback(Boolean aBoolean) {
                if (aBoolean) {
                    getPresenter().removeGoodList(selectData);
                }
            }
        });
        noticeDialog.show();
    }

    /**
     * 删除商品
     *
     * @param goodsModel
     */
    private void removeGood(GoodsModel goodsModel) {

        CancelSureDialog.Builder builder = new CancelSureDialog.Builder(getContext());
        CancelSureDialog dialog = builder.setLeftContent(R.string.yes)
                .setRightContent(R.string.no)
                .setVisibleIcon(false)
                .setVisibleTitleName(false)
                .setContent(R.string.aaa2)
                .setCallBack((Object s) -> {
                    List<GoodsModel> goodsModelList = new ArrayList<>();
                    goodsModelList.add(goodsModel);
                    getPresenter().removeGoodList(goodsModelList);
                })
                .build();
        dialog.show();
    }


    /**
     * 更新数量
     *
     * @param goodsModel
     * @param qty        新的数量
     */
    private void updateGoodForNum(GoodsModel goodsModel, int qty) {
        updateGood(goodsModel, null, qty + "");
    }

    /**
     * 更新属性(颜色,数量,备注,大小等)
     *
     * @param goodsModel
     * @param h5ShopBean
     */
    private void updateGoodForAttr(GoodsModel goodsModel, H5ShopBean h5ShopBean) {
        updateGood(goodsModel, h5ShopBean, null);
    }

    /**
     * 更新商品
     *
     * @param goodsModel
     * @param h5ShopBean
     * @param qty        仅更新数量
     */
    private void updateGood(GoodsModel goodsModel, H5ShopBean h5ShopBean, String qty) {
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("cart_id", goodsModel.getId());
        map.put("session_id", PushHelper.getRegistrationId());
        map.put("member_id", UserInfo.getMemberId());

        //qty
        //remark
        //option
        if (!TextUtils.isEmpty(qty)) {//仅更新数量
            map.put("qty", qty);
//            map.put("remark", goodsModel.getRemark() + "");
//            map.put("option", goodsModel.getOption() + "");
            d("--->>>>>>>>---更新数量");
        } else if (h5ShopBean != null) {//更新数量,备注,颜色尺码
            map.put("qty", h5ShopBean.getNum() + "");
            map.put("remark", h5ShopBean.getRemark() + "");
            map.put("option", h5ShopBean.getAttr() + "");
            d("--->>>>>>>>---更新所有");
        }

        try {
            int qtyI = StringUtils.parseInteger(map.get("qty").toString());
            if (qtyI <= 0) {
                ToastUtil.showToast(String.format(getString(R.string.shopcarpi_minqty_notice), 1));//最低数量是1
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 更新商品属性接口
         */
        getPresenter().updateGood(map);
    }

    protected void submit() {
        List<GoodsModel> selectData = getSelectData();

        if (selectData.size() != 0) {
            ShopCarNoticeDialog noticeDialog = new ShopCarNoticeDialog(getContext(),
                    String.format(getString(R.string.shopcar_submitnotice_title), selectData.size()),
                    "");
            noticeDialog.setCallBack(new WCallBack<Boolean>() {
                @Override
                public void callback(Boolean aBoolean) {
                    if (aBoolean) {
                        Intent intent = new Intent(getContext(), OrderCheckPiActivity.class);
                        intent.putExtra("datas", (Serializable) getSelectIdList());
                        intent.putExtra("isDaigouGoods", true);
                        getContext().startActivity(intent);
                    }
                }
            });
            noticeDialog.show();

        }
    }


    /**
     * 商品全选
     */
    protected void checkAll() {
        for (ShopModel shopModel : mDatas) {
            shopModel.setChecked(!iv_shopcar_checkall.isSelected());
        }
        getCharges();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化事件
     */
    @Override
    protected void initEvent() {
        /**
         * 下拉刷新
         */
        if (auto != null)
            auto.setOnRefreshListener(refreshLayout -> {
                getGoodList(1);
            });

    }

    @Override
    @OnClick({
            R.id.bt_shopcar_submit,
            R.id.tv_shopcar_checkalltext,
            R.id.iv_shopcar_checkall,
            R.id.cons_shop_bottom
    })
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 空点击事件,防止点击下一层布局
             */
            case R.id.cons_shop_bottom:
                break;
            /**
             * 点击全选复选框
             */
            case R.id.tv_shopcar_checkalltext:
            case R.id.iv_shopcar_checkall: {
                checkAll();
            }
            break;
            /**
             *提交审核
             */
            case R.id.bt_shopcar_submit:
                if (TextUtils.equals("0", UserInfo.getUserInfo().getVerified())) {//未认证
                    ToastUtil.showToast(getString(R.string.shopcar_pleaseverify));
                    return;
                }
                submit();
                break;
            default:
                break;
        }
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        super.showLoadingFailureError(throwable);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    /**
     * 获取商品回调
     *
     * @param shopModelList
     */
    @Override
    public void getShopModelListResult(List<ShopModel> shopModelList) {

        mDatas.clear();
        for (ShopModel shopModel : shopModelList) {
            if (shopModel.products != null && shopModel.products.size() > 0) {
                mDatas.add(shopModel);
            }
        }
        mAdapter.notifyDataSetChanged();
        //底部视图是否显示
        cons_shop_bottom.setVisibility(mDatas.size() == 0 ? View.GONE : View.VISIBLE);
        if (mDatas.size() == 0) {
            mAdapter.setEmptyView(emptyView);
        }
        //计算价格
        getCharges();

        ShopRepository.updateShopCount();
        if (isDaigou()) {
            EventBus.getDefault().post(new ShopCarCoutEvent(1, goodsTotal()));
        } else {
            EventBus.getDefault().post(new ShopCarCoutEvent(0, goodsTotal()));
        }
    }

    protected int goodsTotal() {
        int tatal = 0;
        for (ShopModel shopModel : mDatas) {
            if (shopModel.products != null) {
                for (GoodsModel product : shopModel.products) {
                    if (product.canCheck()) {
                        tatal += 1;
                    }
                }
//                tatal += shopModel.products.size();
            }
        }
        return tatal;
    }

    /**
     * 删除购物车商品回调
     *
     * @param resultModel
     * @param goodsModelList
     */
    @Override
    public void removeGoodMallResult(ResultModel resultModel, List<GoodsModel> goodsModelList) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            //重新获取商品集合
            getGoodList(2);
        }

    }

    /**
     * 更新商品属性回调
     *
     * @param resultModel
     */
    @Override
    public void updateGoodResult(ResultModel resultModel) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            //更新购物车商品集合
            getGoodList(2);
        }
    }

    /**
     * 购物车数量变动通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onAddShopCarEvent(AddShopCarEvent event) {
        getGoodList(2);
    }

    /**
     * 提交订单
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onPlaceOrderEvent(PlaceOrderEvent event) {
        getGoodList(2);
    }

    /**
     * 登录变动通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
                //重新获取购物车商品集合
                getGoodList(2);
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                //设置懒加载为无
                hasFetchData = false;
                //重置视图
                resetView();
            }

        }


    }

    /**
     * 付款通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onOrderPayEvent(OrderPayEvent event) {
        //todo 直接跳去处理中订单列表了,所以不需要刷新界面了
//        if (event != null && event.isSuccess()) {
//            //重新获取购物车商品集合
//            getGoodList(2);
//        }

    }

    /**
     * 销毁视图
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private ShopCarListener shopCarListener = new ShopCarListener() {
        @Override
        public void startGoodsDetailsActivity(GoodsModel goodsModel) {
            GoodsDetailsActivity.startGoodsDetailsActivity(mContext, goodsModel.getProduct_id());
        }

        @Override
        public void addGoods(GoodsModel goodsModel, int newQty) {
            updateGoodForNum(goodsModel, newQty);
        }

        @Override
        public void editGoods(GoodsModel goodsModel) {
            ShopUpdateDialogFragment shopUpdateDialogFragment = ShopUpdateDialogFragment.newInstance(goodsModel);
            shopUpdateDialogFragment.show(getChildFragmentManager(), "ShopCarFragment");
        }

        @Override
        public void deleteGoods(GoodsModel goodsModel) {
            removeGood(goodsModel);
        }

        @Override
        public void selectGoods(ShopModel shopModel, GoodsModel goodsModel) {
            boolean isChecked = goodsModel.isChecked();
            if (goodsModel.is1688()) {
                for (GoodsModel item : shopModel.products) {
                    if (item.getProduct_id() == goodsModel.getProduct_id()) {
                        item.setChecked(!isChecked);
                    }
                }
            } else {
                goodsModel.setChecked(!isChecked);
            }
            mAdapter.notifyDataSetChanged();
            getCharges();
        }

        @Override
        public void selectGoods(List<GoodsModel> goodsModelList) {
            mAdapter.notifyDataSetChanged();
            getCharges();
        }

        @Override
        public boolean isDaigouGoods() {
            return isDaigou();
        }

    };

}